<template>
	<Codemirror
		v-model:value="code"
		:options="cmOptions"
		ref="cmRef"
		height="400"
		width="600"
		@change="onChange"
		@input="onInput"
		@ready="onReady"
	>
	</Codemirror>
</template>
<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useDebounceFn } from "@vueuse/core";
import Codemirror from "codemirror-editor-vue3";
import jsonlint from "jsonlint-mod";
// language json or js
import "codemirror/mode/javascript/javascript.js";
import "codemirror/addon/lint/lint.css";
import "codemirror/addon/lint/lint.js";
import "codemirror/addon/lint/json-lint";
window.jsonlint = jsonlint;
const code = computed(() => {
	return props.value;
});
const props = defineProps({
	value: {
		type: String,
		default: "",
	},

	height: {
		type: String,
		default: "200px",
	},

	width: {
		type: String,
		default: "100%",
	},
});
const emit = defineEmits(["setCodeValue"]);
const cmRef = ref();
const cmOptions = {
	tabSize: 2, // tab
	styleActiveLine: true, // 高亮选中行
	lineNumbers: true, // 显示行号
	lineWrapping: true,
	styleSelectedText: true,
	line: true,
	foldGutter: false, // 块槽
	// gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
	highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true }, // 可以启用该选项来突出显示当前选中的内容的所有实例
	// 模式, 可查看 codemirror/mode 中的所有模式
	mode: {
		name: "javascript",
		json: true,
	},
	hintOptions: {
		// 当匹配只有一项的时候是否自动补全
		completeSingle: false,
	},
	// 快捷键 可提供三种模式 sublime、emacs、vim
	// keyMap: "sublime",
	matchBrackets: true,
	showCursorWhenSelecting: true,
	theme: "idea", // 主题
	extraKeys: { Ctrl: "autocomplete" }, // 可以用于为编辑器指定额外的键绑定，以及keyMap定义的键绑定,

	cursorHeight: 0.94,
};

const onChange = useDebounceFn((val, cm) => {
	console.log("val", val);
	emit("setCodeValue", val);
}, 1000);

const onReady = (cm) => {
	if (props.height != "auto") {
		cmRef.value?.resize(props.width, props.height);
	} else {
		cmRef.value?.resize(props.width);
	}
};

onUnmounted(() => {
	cmRef.value?.destroy();
});
</script>
<style>
.CodeMirror-scroll {
	overflow: scroll !important;
	margin-bottom: 0;
	margin-right: 0;
	padding-bottom: 0;
	/*height: 100%;*/
	outline: none;
	position: relative;
	/*border: 1px solid #dddddd;*/
}
.code-mirror {
	font-size: 13px;
	line-height: 150%;
	text-align: left;
}

.CodeMirror {
	border: 1px solid #dddddd;
	height: auto;
}
</style>
